﻿using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Albatross.SharePoint.Explorer.ViewModels {
	public class ViewFieldCollectionViewModel : ClientObjectCollectionViewModel {

		public ViewFieldCollection ViewFieldCollection { get { return (ViewFieldCollection)ClientObjectCollection; } }
		
		public const string ViewFieldsPropertyName = "ViewFields";
		private IEnumerable<string> _viewFields;
		public IEnumerable<string> ViewFields {
			get { return _viewFields; }
			set {
				if (_viewFields == value) { return; }
				RaisePropertyChanging(ViewFieldsPropertyName);
				_viewFields = value;
				RaisePropertyChanged(ViewFieldsPropertyName);
			}
		}


		public ViewFieldCollectionViewModel(ClientContext context, string name, ViewFieldCollection viewFields) : base(context, name, viewFields) { }
		protected override Tuple<IEnumerable<ObjectProperty>, IEnumerable<ClientObjectViewModel>> Load() {
			Type type = ClientObjectCollection.GetType();
			List<ObjectProperty> properties = new List<ObjectProperty>();
			List<ClientObjectViewModel> children = new List<ClientObjectViewModel>();
			Tuple<IEnumerable<ObjectProperty>, IEnumerable<ClientObjectViewModel>> tuple = new Tuple<IEnumerable<ObjectProperty>, IEnumerable<ClientObjectViewModel>>(properties, children);

			Context.Load(ClientObjectCollection);
			Context.ExecuteQuery();


			foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty)) {
				if (property.PropertyType == typeof(string) || property.PropertyType.IsValueType) {
					if (property.Name == SchemaXml_Property) {
						HasSchemaXml = true;
					} else {
						properties.Add(new ObjectProperty().Set(ClientObject, property));
					}
				}
			}
			ViewFields = ViewFieldCollection;
			return tuple;
		}
	}
}
